package com.tuozixuan;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

public class Test {

	public static void main(String[] args) {
//		new Test().executeCommand("java -version");
//		new Test().executeCommand("mvn.cmd -v");
//		new Test().executeCommand("D:\\system\\apache-maven-3.5.4\\bin\\mvn.cmd -v");
		new Test().executeCommand("echo %MAVEN_HOME%");
		
		String mavenHome = System.getenv("MAVEN_HOME");
		System.out.println("mavenHome:" + mavenHome);
	}

    public String executeCommand(String command, String params) {
        String line = String.format("%s %s", command, params);
        return execute(line);
    }

    public String executeCommand(String command) {
        return execute(command);
    }

    private String execute(String line) {
        CommandLine commandLine = CommandLine.parse(line);
        DefaultExecutor defaultExecutor = new DefaultExecutor();
        defaultExecutor.setExitValues((int[]) null);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000L);
        defaultExecutor.setWatchdog(watchdog);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ByteArrayOutputStream es = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
        defaultExecutor.setStreamHandler(streamHandler);
        String out = "";
        String err = "";

        try {
            defaultExecutor.execute(commandLine);
            out = os.toString(StandardCharsets.UTF_8.name());
            err = es.toString(StandardCharsets.UTF_8.name());
            System.out.println("out:" + out);
            System.out.println("err:" + err);
        } catch (IOException var16) {
            //log.warn("defaultExecutor exe command IO error:", var16);
        	var16.printStackTrace();
        }

        if (err != null && err.length() > 0) {
            //log.error("execute command {} error:{}", line, err);
            throw new RuntimeException("execute command " + line + "\n error " + err);
        } else {
            return out;
        }
    }

}
